package com.zjl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjl.common.CustomException;
import com.zjl.entity.Category;
import com.zjl.entity.Dish;
import com.zjl.entity.Setmeal;
import com.zjl.mapper.CategoryMapper;
import com.zjl.service.CategoryService;
import com.zjl.service.DishService;
import com.zjl.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    /**
     * 根据id删除分类,删除前查询当前分类是否仍关联菜品或者套餐，若有则不删除
     * @param id
     */
    @Override
    public void remove(Long id) {


        //查询当前分类是否仍关联菜品，若有关联，抛出业务异常
            //添加查询条件,根据CategoryId进行查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(dishLambdaQueryWrapper);
        if (count1>0){
            //当前分类已经关联菜品，抛出异常.让全局异常处理器进行捕获
            throw new CustomException("当前分类下关联菜品，无法删除");
        }

        //查询当前分类是否仍关联套餐，若有关联，抛出业务异常
            //添加查询条件,根据CategoryId进行查询
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper=new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2>0){
            //当前分类已经关联，抛出异常
            throw new CustomException("当前分类下关联套餐，无法删除");
        }

        //正常删除分类
        super.removeById(id);

    }
}
